package freaks.terah.gui;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.border.TitledBorder;
import javax.swing.border.EtchedBorder;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.JComboBox;

import freaks.terah.model.Data;
import freaks.terah.model.PlayerModel;
import freaks.terah.model.Unit;

public class MissionFrame extends JPanel implements ActionListener, ItemListener{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private PlayerModel theModel;
	private JComboBox targetBox;
	private JComboBox shipBox;
	private JComboBox soldierBox;
	private JComboBox technicianBox; 
	private JComboBox missionTypeBox;
	private JLabel lblShip;
	private JPanel planet1 = null;
	private JPanel planet2 = null;
	private JPanel planet3 = null;
	private JLabel noPlanetLbl;
	private JLabel lblPower;
	private JLabel lblBrain;
	private JLabel lblDefense;
	private JLabel lblCarry;
	private Gui guiParent;
	private JLabel lblTarget;
	private JLabel lblcollectres;
	private int[] globalStats;

	/**
	 * Create the panel.
	 */
	public MissionFrame(PlayerModel model, Gui aGuiParent) {
		theModel = model;
		guiParent = aGuiParent;
		setLayout(null);
		
		JPanel panel_1 = new JPanel();
		panel_1.setBorder(new TitledBorder(null, "Environment", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		panel_1.setBounds(4, 35, 205, 445);
		add(panel_1);
		panel_1.setLayout(null);
		
		noPlanetLbl = new JLabel("No Planet");
		noPlanetLbl.setBounds(panel_1.getWidth()/2-100, panel_1.getHeight()/2-8, 200, 16);
		noPlanetLbl.setVisible(false);
		noPlanetLbl.setHorizontalAlignment(JLabel.CENTER);
		panel_1.add(noPlanetLbl);
		
		planet1 = new JPanel();
		planet1.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Planet 1", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
		planet1.setBounds(6, 25, 193, 128);
		planet1.setVisible(false);
		panel_1.add(planet1);
		planet1.setLayout(null);
		
		planet2 = new JPanel();
		planet2.setBorder(new TitledBorder(null, "Planet 2", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		planet2.setBounds(6, 165, 193, 128);
		planet2.setVisible(false);
		panel_1.add(planet2);
		planet2.setLayout(null);
		
		planet3 = new JPanel();
		planet3.setBorder(new TitledBorder(null, "Planet 3", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		planet3.setBounds(6, 305, 193, 128);
		planet3.setVisible(false);
		panel_1.add(planet3);
		planet3.setLayout(null);
		
		JPanel panel_2 = new JPanel();
		panel_2.setBounds(221, 35, 465, 445);
		add(panel_2);
		panel_2.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Mission Planning", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
		panel_2.setLayout(null);
		
		missionTypeBox = new JComboBox();
		DefaultComboBoxModel missionTypes = new DefaultComboBoxModel();
		missionTypes.addElement("Land on planet");
		missionTypes.addElement("Spy rival");
		missionTypes.addElement("Attack rival");
		missionTypes.addElement("Scrounge");
		missionTypeBox.setBounds(111, 352, 200, 27);
		missionTypeBox.setModel(missionTypes);
		missionTypeBox.addItemListener(this);
		panel_2.add(missionTypeBox);
		
		JLabel lblMissionType = new JLabel("Mission Type:");
		lblMissionType.setBounds(22, 356, 97, 16);
		panel_2.add(lblMissionType);
		
		lblTarget = new JLabel("Target:");
		lblTarget.setBounds(22, 396, 85, 16);
		panel_2.add(lblTarget);
		
		targetBox = new JComboBox();
		targetBox.setBounds(111, 392, 140, 27);
		panel_2.add(targetBox);
		
		shipBox = new JComboBox();
		shipBox.setBounds(111, 29, 253, 27);
		shipBox.setModel(theModel.getShipList());
		shipBox.setRenderer(theModel.getRessourceRenderer());
		shipBox.addItemListener(this);
		panel_2.add(shipBox);
		
		lblShip = new JLabel("Ship:");
		lblShip.setBounds(22, 33, 97, 16);
		panel_2.add(lblShip);
		
		soldierBox = new JComboBox();
		soldierBox.setBounds(111, 68, 253, 27);
		soldierBox.setModel(theModel.getSoldierList());
		soldierBox.setRenderer(theModel.getRessourceRenderer());
		soldierBox.addItemListener(this);
		panel_2.add(soldierBox);
		
		JLabel lblSoldier = new JLabel("Soldier:");
		lblSoldier.setBounds(22, 72, 97, 16);
		panel_2.add(lblSoldier);
		
		technicianBox = new JComboBox();
		technicianBox.setBounds(111, 107, 253, 27);
		technicianBox.setModel(theModel.getTechnicianList());
		technicianBox.setRenderer(theModel.getRessourceRenderer());
		technicianBox.addItemListener(this);
		panel_2.add(technicianBox);
		
		JLabel lblExpert = new JLabel("Technician:");
		lblExpert.setBounds(22, 111, 97, 16);
		panel_2.add(lblExpert);
		
		lblPower = new JLabel("Power: ");
		lblPower.setBounds(22, 158, 85, 27);
		panel_2.add(lblPower);
		
		lblBrain = new JLabel("Brain: ");
		lblBrain.setBounds(122, 158, 85, 27);
		panel_2.add(lblBrain);
		
		lblDefense = new JLabel("Defense:");
		lblDefense.setBounds(222, 158, 85, 27);
		panel_2.add(lblDefense);
		
		lblCarry = new JLabel("Carry:");
		lblCarry.setBounds(322, 158, 85, 27);
		panel_2.add(lblCarry);
		
		lblcollectres = new JLabel("Collectable Ressources:");
		lblcollectres.setBounds(22, 197, 325, 16);
		panel_2.add(lblcollectres);
		
		JLabel lblBonuses = new JLabel("Bonus(es):");
		lblBonuses.setBounds(22, 229, 74, 16);
		panel_2.add(lblBonuses);
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
	}
	
	private int[] addArrays(int[] a, int[] b)
	{
		for (int i = 0; i < a.length; i++)
			a[i] = a[i] + b[i];
		
		return a;
	}

	@Override
	public void itemStateChanged(ItemEvent arg0) {
		if ((arg0.getSource() == shipBox || arg0.getSource() == soldierBox || arg0.getSource() == technicianBox) && arg0.getStateChange() == ItemEvent.SELECTED)
		{
			updateDisplay();
		}
		
		if (arg0.getSource() == missionTypeBox && arg0.getStateChange() == ItemEvent.SELECTED)
		{
			setTarget((String) arg0.getItem());
		}
	}
	
	private void setTarget(String event) {
		targetBox.setVisible(true);
		lblTarget.setVisible(true);
		
		if (event.equalsIgnoreCase("Land on planet"))
		{
			DefaultComboBoxModel targets = new DefaultComboBoxModel();
			
			if (planet1 != null)
				targets.addElement("Planet 1");
			if (planet2 != null)
				targets.addElement("Planet 2");
			if (planet3 != null)
				targets.addElement("Planet 3");
			
			targetBox.setModel(targets);
		}
		
		if (event.equalsIgnoreCase("Spy rival") || event.equalsIgnoreCase("Attack rival"))
		{
            DefaultComboBoxModel targets = new DefaultComboBoxModel();
			for (int i = 0; i < guiParent.getPlayers().size(); i++)
				if (i+1 != theModel.getPlayerNumber())
					targets.addElement(guiParent.getPlayers().get(i));
			
			targetBox.setModel(targets);
		}
		
		if (event.equalsIgnoreCase("Scrounge"))
		{
			lblShip.setText("Scrounge");
			targetBox.setVisible(false);
			lblTarget.setVisible(false);
		}
	}

	private void updateDisplay() {
		Unit theShip = (Unit) shipBox.getSelectedItem();
		Unit theSoldier = (Unit) soldierBox.getSelectedItem();
		Unit theTechnician = (Unit) technicianBox.getSelectedItem();
		if (theShip != null && theSoldier != null && theTechnician != null)
		{
			int[] stats = {0,0,0,0,0}; 
			stats = addArrays(stats, theShip.getStats());
			stats = addArrays(stats, theSoldier.getStats());
			stats = addArrays(stats, theTechnician.getStats());
			
			globalStats = stats;

			lblPower.setText("Power: " + String.valueOf(stats[0]));
			lblDefense.setText("Defense: " + String.valueOf(stats[1]));
			lblBrain.setText("Brain: " + String.valueOf(stats[2]));
			lblCarry.setText("Carry: " + String.valueOf(stats[3]));
			
			String label = ((stats[4] & 1) == 1 ? "Fo " : "") +
			(((stats[4] & 2) >> 1) == 1 ? "Fu " : "") +
			(((stats[4] & 4) >> 2) == 1 ? "E " : "") +
			(((stats[4] & 8) >> 3) == 1 ? "Sc " : "") +
			(((stats[4] & 16) >> 4) == 1 ? "M " : "") +
			(((stats[4] & 32) >> 5) == 1 ? "C " : "");
			
			lblcollectres.setText("Collectable Ressources: " + label);
		}
	}

	public void setServerData(Data[] data) throws Exception
	{
		int type = Integer.parseInt(data[0].getData());
		
		int planets = Integer.parseInt(data[1].getData());
		int total = 2;
		int ressourcesType = 3;
			
		if (type > 0)
		{
			for (int i = 0; i < planets;i++)
			{
				JPanel aPlanet = getPlanet(i);
				int planetType = Integer.parseInt(data[total+i].getData());
				JLabel typeLabel = new JLabel("Type: " + getPlanetType(planetType));
				if (type == 1)
				{
					typeLabel.setBounds(aPlanet.getWidth()/2-100, aPlanet.getHeight()/2-8, 200, 16);
					typeLabel.setHorizontalAlignment(JLabel.CENTER);
				}
				else
				{
				    typeLabel.setBounds(aPlanet.getWidth()/2-100, 26, 200, 16);
				    typeLabel.setHorizontalAlignment(JLabel.CENTER);
				}
				
				aPlanet.add(typeLabel);
			}
			
			total = 5;
		}
		
		if (type == 2)
		{
			for (int i = 0; i < planets;i++)
			{
				JPanel aPlanet = getPlanet(i);
			    JLabel resLabel = new JLabel("Available Ressources");
			    resLabel.setBounds(aPlanet.getWidth()/2-100, 46, 200, 16);
			    resLabel.setHorizontalAlignment(JLabel.CENTER);

			    String label = (Integer.parseInt(data[total+i*6].getData()) == 1 ? "Fo " : "") +
			                   (Integer.parseInt(data[total+1+i*6].getData()) == 1 ? "Fu " : "") +
			                   (Integer.parseInt(data[total+2+i*6].getData()) == 1 ? "E " : "") +
			                   (Integer.parseInt(data[total+3+i*6].getData()) == 1 ? "Sc " : "") +
			                   (Integer.parseInt(data[total+4+i*6].getData()) == 1 ? "M " : "") +
			                   (Integer.parseInt(data[total+5+i*6].getData()) == 1 ? "C " : "");

			    JLabel ressourceLabel = new JLabel(label);
			    ressourceLabel.setBounds(aPlanet.getWidth()/2-100, 66, 200, 16);
			    ressourceLabel.setHorizontalAlignment(JLabel.CENTER);
			    aPlanet.add(resLabel);
			    aPlanet.add(ressourceLabel);
			}
			
			total = 23;
		}
		
		if (type > 2)
		{
			for (int i = 0; i < planets;i++)
			{
				JPanel aPlanet = getPlanet(i);
			    JLabel resLabel = new JLabel("Available Ressources");
			    resLabel.setBounds(aPlanet.getWidth()/2-100, 46, 200, 16);
			    resLabel.setHorizontalAlignment(JLabel.CENTER);

			    String label = (Integer.parseInt(data[total+i*6].getData()) == 1 ? "Fo " : "") +
			                   (Integer.parseInt(data[total+1+i*6].getData()) == 1 ? "Fu " : "") +
			                   (Integer.parseInt(data[total+2+i*6].getData()) == 1 ? "E " : "") +
			                   (Integer.parseInt(data[total+3+i*6].getData()) == 1 ? "Sc " : "") +
			                   (Integer.parseInt(data[total+4+i*6].getData()) == 1 ? "M " : "") +
			                   (Integer.parseInt(data[total+5+i*6].getData()) == 1 ? "C " : "");

			    JLabel ressourceLabel = new JLabel(label);
			    ressourceLabel.setBounds(aPlanet.getWidth()/2-100, 66, 200, 16);
			    ressourceLabel.setHorizontalAlignment(JLabel.CENTER);
			    aPlanet.add(resLabel);
			    aPlanet.add(ressourceLabel);
			}
			
			total = 23;
		}
		
		if (type > 3)
		{
			for (int i = 0; i < planets;i++)
			{
				JPanel aPlanet = getPlanet(i);
			    JLabel resLabel = new JLabel("Available Ressources");
			    resLabel.setBounds(aPlanet.getWidth()/2-100, 46, 200, 16);
			    resLabel.setHorizontalAlignment(JLabel.CENTER);

			    String label = (Integer.parseInt(data[total+i*3].getData()) == 1 ? "Attack: " : "") +
			                   (Integer.parseInt(data[total+1+i*3].getData()) == 1 ? "Defense: " : "") +
			                   (Integer.parseInt(data[total+2+i*3].getData()) == 1 ? "Brain: " : "");

			    JLabel ressourceLabel = new JLabel(label);
			    ressourceLabel.setBounds(aPlanet.getWidth()/2-100, 66, 200, 16);
			    ressourceLabel.setHorizontalAlignment(JLabel.CENTER);
			    aPlanet.add(resLabel);
			    aPlanet.add(ressourceLabel);
			}
			
			total = 32;
			ressourcesType = 4;
		}
		
		if (type == 0)
		{
			for (int i = 0; i < planets;i++)
			{
				JPanel aPlanet = getPlanet(i);
				JLabel noInfo = new JLabel("No Info");
				noInfo.setBounds(aPlanet.getWidth()/2-50, aPlanet.getHeight()/2-8, 100, 16);
				noInfo.setHorizontalAlignment(JLabel.CENTER);
				aPlanet.add(noInfo);
			}
		}
		
		for (int i = 0; i < planets;i++)
		{
			JPanel aPlanet = getPlanet(i);
			aPlanet.setVisible(true);
		}
		
		if (planets == 0)
		{
			setTarget("Spy rival");
			noPlanetLbl.setVisible(true);
		} else
			setTarget("Land on planet");
		
		String stuff = "";
		for (int i = 0; i < ressourcesType;i++)
		{
			int quantityType = Integer.parseInt(data[total+i*2].getData());
			int quantityValue = Integer.parseInt(data[total+1+i*2].getData());
			String newValue = "";
			if (quantityValue != 0)
			{
				String qType = "";
				
				switch (quantityType)
				{
				case 0:
					qType = "Food";
					break;
				case 1:
					qType = "Fuel";
					break;
				case 2:
					qType = "Energy";
					break;
				case 3:
					qType = "Scrap";
					break;
				case 4:
					qType = "Machine";
					break;
				case 5:
					qType = "Crystal";
					break;
				case 6:
					qType = "Support";
					break;
				case 8:
					qType = "Insight";
					break;
				case 9:
					qType = "";
					break;
				}
				
				if (quantityType != 9)
				{
					newValue = data[total+1+i*2].getData() + " " + qType;
				} else
				{
					String techType = "";
					
					// TODO: Techs case
					
					newValue = "1 " + techType;
				}
			}
			
			if (newValue != "")
			{
			    if (stuff != "")
			    	stuff += ", " + newValue;
			    else
			    	stuff += newValue;
			}
		}
		
		if (stuff == "")
			JOptionPane.showMessageDialog(null, "You have gotten nothing! Too bad!");
		else
			JOptionPane.showMessageDialog(null, "You have gotten: " + stuff);
		
		updateDisplay();
	}
	
	public Data[] getServerData()
	{
		String type = (String) missionTypeBox.getSelectedItem();
		
		return new Data[]{
				new Data(getMissionType(type)),
				new Data(targetBox.getSelectedIndex() < theModel.getPlayerNumber()-1 ? targetBox.getSelectedIndex() : targetBox.getSelectedIndex() + 1 ),
				new Data(globalStats[0]),
				new Data(globalStats[1]),
				new Data(globalStats[2]),
				new Data(globalStats[3]),
				new Data(globalStats[4]),
				new Data(theModel.getPlayerRessources()[7]),
				new Data(0)
		};
	}
	
	private int getMissionType(String s)
	{
		if (s.equalsIgnoreCase(""))
			return 0;
		if (s.equalsIgnoreCase("Land on planet"))
			return 1;
		if (s.equalsIgnoreCase("Spy rival"))
			return 2;
		if (s.equalsIgnoreCase("Attack rival"))
			return 3;
		if (s.equalsIgnoreCase("Scrounge"))
			return 4;
		
		return 0;
	}
	
	private JPanel getPlanet(int index)
	{
		if (index == 0)
			return planet1;
		else if (index == 1)
			return planet2;
		else if (index == 2)
			return planet3;
		
		return null;
	}
	
	private String getPlanetType(int ID)
	{
		switch (ID)
		{
		    case 0:
			    return "Grass World";
		    case 1:
		    	return "Dirt World";
		    case 2:
		    	return "Lava World";
		}
		
		return "Unknown World";
	}
}
